<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form name="regForm"">
    <div>用户名：<input type="text" name="username" value="admin">
        <span class="error-msg" hidden>用户名不得为空</span>
    
    </div>
    <div>密码：<input type="password" name="password" value="pwd"></div>
    <div>
        性别：
        <select name="gender">
            <option value="male">男</option>
            <option value="female">女</option>
        </select>
    </div>
    <div>
        爱好：
        <input type="checkbox" name="hobby" value="sport" checked/>运动
        <input type="checkbox" name="hobby" value="reading"/>阅读

    </div>
    <div>
        <button type="submit" onclick="alert('提交成功')">提交</button>
        <button type="rest">重置</button>
    </div>
    
    </form>

    <script>
        const regForm = document.forms.regForm;
        console.log(regForm.username.value);
        console.log(regForm.password.value);
        console.log(regForm.gender.value);
        console.log(regForm.hobby.value);
        //获取checkbox的value值
        regForm.hobby.forEach((it) =>{
            if(it.checked){
                console.log(it.value);
            }
        });

        //获取焦点
        //事件 focus获取事件，blur失去焦点
        regForm = document.getElementById("regForm");
        const username = regForm.querySelector("input[name'username']");
        username.addEventListener("blur",(event)=>{
            if(!username.value.trim()){
                const errorMsg = username.closest("div").querySelector(".error-msg");
                errorMsg.hidden = false;
            });

        //通过FormData来提取表单数据
        regForm.addEventListener("submit",(event)=>{
            //阻止浏览器的默认行为
            event.preventDefault();
            const formData = new FormaData(regForm);
            const formObj = Object.fromEntries(formData);
            formObj.hobby = formData.getAll("hobby");
            console.log(formObj);
            });

        // //表单提交事件  submit
        // regForm.addEventListener("submit",(event)=>{
        //     //阻止浏览器的默认行为
        //     event.preventDefault();
        //     const formObj = {
        //         username: regForm.username.value,
        //         password: regForm.password.value,
        //         gender: regForm.gender.value,
        //         hobby: [...regForm.hobby].filter((it) => it.checked).map((it) => it.value)
        //     };
        //     console.log(formObj);
        // });
            
    </script>
</body>
</html>